<template>
  <view>
    <l-navigation-bar
      id="navigationBar"
      :color="colorT1"
      title="统计"
      bg-color="#ffffff"
      :immerse="immerse"
      :scroll-top="scrollTop"
    />
    <!-- #ifdef APP-PLUS -->
    <l-status-bar />
    <!-- #endif -->

    <view class="padding-top-30 padding-lr-30 margin-bottom-20">
      <summary-card title="总收入(元)" :total-amount="totalAmount" :info="statistics" />
    </view>

    <view class="padding-lr-30 padding-top-20 bg-white date-filter" :style="{top:top+'px'}">
      <view class="padding-bottom-20 ">
        <date-filter :start-time="startTime" :end-time="endTime" @recentUpdate="dateChange" @change="change" />
      </view>
    </view>

    <view class="padding-lr-30 padding-bottom-30">
      <view class="padding-top-20">
        <vehicle-model ref="vehicle" :end-time="endTime" :start-time="startTime" :max="6" />
      </view>

      <view class="padding-top-50">
        <driver-model ref="driver" :end-time="endTime" :start-time="startTime" :max="8" />
      </view>

      <view class="padding-top-50">
        <order-model :order-source="orderSource" />
      </view>

      <view class="padding-top-50">
        <pay-type-model :order-pay-way="orderPayWay" />
      </view>

      <view class="padding-top-50">
        <driver-status-model ref="driverStatus" :end-time="endTime" :start-time="startTime" />
      </view>
    </view>

    <!-- #ifndef APP-PLUS -->
    <tui-calendar
      ref="calendar"
      :init-start-date="startTime"
      :init-end-date="endTime"
      @change="dateChange"
    />
    <!-- #endif -->

    <view v-if="noPermission" class="no-permission">
      <l-no-data type="permission" text="暂无权限" />
    </view>
  </view>
</template>

<script>
import DateFilter from './components/date-filter/date-filter'
import VehicleModel from './components/vehicle-model/vehicle-model'
import DriverModel from './components/driver-model/driver-model'
import OrderModel from './components/order-model/order-model'
import PayTypeModel from './components/pay-type-model/pay-type-model'
import DriverStatusModel from './components/driver-status-model/driver-status-model'
import colors from '@/common/colors'
import { mapGetters } from 'vuex'
import { dateFormat } from '@/common/util'
import { openSubView } from '@/common/plus'
import { summary, fetchVehicleOrderSummary } from '@/common/api/statistics.js'
const refs = ['vehicle', 'driver', 'driverStatus']
export default {
  name: 'Statistics',
  components: {
    DateFilter,
    VehicleModel,
    DriverModel,
    OrderModel,
    PayTypeModel,
    DriverStatusModel
  },
  data() {
    const startTime = dateFormat(new Date().setDate(1))
    const endTime = dateFormat()
    let immerse = false
    /* #ifdef APP-PLUS*/
    immerse = true
    /* #endif*/
    return {
      top: 0,
      totalAmount: 0,
      statistics: [
        { label: '订单数(笔)', value: 0, fixed: false },
        { label: '平均客单价(元)', value: 0, fixed: true },
		{ label: '车均收入(元)', value: 0, fixed: true }
      ],
      startTime,
      endTime,
      orderSource: {},
      orderPayWay: {},
      scrollTop: 0,
      immerse,
      calendarInx: 0,
      noPermission: false,
      colorT1: colors.fontcolorT1
    }
  },
  computed: {
    ...mapGetters({
      auth: 'auth'
    })
  },
  onShow() {
    this.noPermission = !this.auth.includes('statistics_view')
    this.getData()
  },
  created() {
    uni.$on('changeStatisticsDate', e => {
      this.dateChange(e)
      this.calendarInx = e.inx
    })
  },
  mounted() {
    this.getTop()
    uni.$emit('setStatisticsDate', {
      startTime: this.startTime,
      endTime: this.endTime
    })
  },
  beforeDestroy() {
    uni.$off('changeStatisticsDate')
  },
  /* #ifdef APP-PLUS*/
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
  },
  /* #endif*/
  methods: {
    getTop() {
      setTimeout(() => {
        this.getElementInfo('#navigationBar', res => {
          this.top = res.height
        })
      }, 300)
    },
    getData() {
      this.fetchOrderSummery()
      refs.forEach(key => {
        const ref = this.$refs[key]
        if (ref || ref !== undefined) ref.getData()
      })
    },
    async fetchOrderSummery() {
      const [err, res] = await summary({
        startTime: this.startTime + ' 00:00:00',
        endTime: this.endTime + ' 23:59:59'
      })
      uni.stopPullDownRefresh()
      if (!this.$http.errorCheck(err, res)) return false
      const data = res.data.data
      await this.fetchVehicleOrderSummary(data.totalAmount)
      this.totalAmount = data.totalAmount
      this.statistics[0].value = data.total

      if (data.total !== '0') this.statistics[1].value = data.totalAmount / data.total
      else this.statistics[1].value = 0

      this.orderSource = {
        innerOrderAmount: data.innerOrderAmount,
        innerOrderCount: data.innerOrderCount,
        platformOrderAmount: data.platformOrderAmount,
        platformOrderCount: data.platformOrderCount,
        total: data.total
      }

      this.orderPayWay = {
        creditOrderAmount: data.creditOrderAmount,
        creditOrderCount: data.creditOrderCount,
        prepayOrderAmount: data.prepayOrderAmount,
        prepayOrderCount: data.prepayOrderCount
      }
      this.orderIncome = [data.hasPayOrderAmount, data.unPayOrderAmount]
    },
    async fetchVehicleOrderSummary(totalAmount) {
      const [err, res] = await fetchVehicleOrderSummary({
        startTime: this.startTime + ' 00:00:00',
        endTime: this.endTime + ' 23:59:59',
        start: 0,
        limit: 9999
      })
      if (!this.$http.errorCheck(err, res)) return false
      const data = res.data.data
      if (data.length) this.statistics[2].value = totalAmount / data.length
      else this.statistics[2].value = 0
    },
    change() {
      /* #ifndef APP-PLUS*/
      this.$refs.calendar.show()
      /* #endif*/
      /* #ifdef APP-PLUS*/
      openSubView('/pages/statistics/components/calendar/calendar', 'slide-in-bottom', 11, 'calendar-mask')
      setTimeout(() => {
        uni.$emit('setStatisticsDate', {
          startTime: this.startTime,
          endTime: this.endTime
        })
      }, 100)
      /* #endif*/
    },
    dateChange(e) {
      this.startTime = e.startDate
      this.endTime = e.endDate
      setTimeout(() => {
        this.getData()
      }, 100)
    }
  }
}
</script>

<style scoped lang="scss">
.date-filter{
  @include position(sticky);
  z-index:800;
}
.no-permission{
  @include position(fixed,0,0,0,0);
  background:$color-background;
  z-index:1000;
}
</style>
